/*
 * Image.cpp
 *
 *  Created on: Jul 7, 2009
 *      Author: kurt
 */

#include "Image.h"
#include "DrawingCanvas.h"
#include "Types.h"
#include "GraphicsInstance.h"
#include <GL/gl.h>
#include <malloc.h>
#include <cstring>
#include <sstream>
#include <math.h>
#include "ImageUtil.h"
using namespace std;
using namespace objdraw;

Image::~Image() 
{
	if(data.texid > 0)
		glDeleteTextures(1,&data.texid);
	if(data.data != NULL)
	{
		free(data.data);
		data.data = NULL;
	}
}
Image::Image(Image const & r)
{
	
}
Image::Image(DrawingCanvas * c)
{
	start = Location(0,0);
	end = Location(0,0);
	color = Color(0,0,0);
	hidden = false;
	memset(&data,0,sizeof(Image::ImageData));
	canvas = c;
	mirroredVert = mirroredHori = false;
	if(canvas != NULL)
		canvas->getCanvasContent().addDrawable(this);
}
uint Image::getPixel(uint x, uint y)
{
	if(data.data == NULL)
		return 0;
	int index = (y * data.width) + x;
	if(index >= data.size)
		return 0;
	return data.data[index];
}
void Image::setPixel(uint x, uint y, uint pixel)
{
	if(data.data == NULL)
		return;
	int index = (y * data.width) + x;
	if(index >= data.size)
		return;
	data.data[index] = pixel;
}
uint Image::getImageWidth()
{
	return data.width;
}
uint Image::getImageHeigth()
{
	return data.height;
}
GLuint & Image::getTexId()
{
	return data.texid;
}
bool Image::isMirroredVert()
{
	return mirroredVert;
}
bool Image::isMirroredHori()
{
	return mirroredHori;
}
void Image::mirrorVert()
{
	mirroredVert = true;
}
void Image::mirrorHori()
{
	mirroredHori = true;
}
void Image::setVertMirror(bool mir)
{
	mirroredVert = mir;
}
void Image::setHoriMirror(bool mir)
{
	mirroredHori = mir;
}
void Image::render()
{
	if(hidden || data.texid <= 0) 
		return;
	
// we do not need to test for depth and enable 2d
	glEnable2D();
	glDisable(GL_DEPTH_TEST); 
	glEnable(GL_TEXTURE_2D);
	
//	flipTextureMatrix();
	
	glColor3f( 1.0f, 1.0f, 1.0f );
// setting the texture
	glBindTexture(GL_TEXTURE_2D,data.texid);
	
	float widthRatio = ((float )(data.width))/((float)data.textureWidth);
	float heightRatio = ((float)(data.height))/((float)data.textureHeight);
	glBegin(GL_QUADS);
		glTexCoord2f(!mirroredVert ? 0.0f : widthRatio, !mirroredHori ? 0.0f : heightRatio);
		glVertex2f(start.x, start.y);
		
		glTexCoord2f(!mirroredVert ? widthRatio : 0.0f, !mirroredHori ? 0.0f : heightRatio);
		glVertex2f(end.x, start.y);
		
		glTexCoord2f(!mirroredVert ? widthRatio : 0.0f, !mirroredHori ? heightRatio : 0.0f);
		glVertex2f(end.x, end.y);
		
		glTexCoord2f(!mirroredVert ? 0.0f : widthRatio, !mirroredHori ? heightRatio : 0.0f);
		glVertex2f(start.x, end.y);
	glEnd();
	
// enable the depthtesting again.
	glEnable(GL_DEPTH_TEST); 
	glDisable(GL_TEXTURE_2D);
	glDisable2D();

}
